import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  SafeAreaView,
  StatusBar,
  TextInput,
  Modal,
  Alert,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';

// Simple text-based icons
const Icon = ({ name, size = 24, color = '#000' }: { name: string; size?: number; color?: string }) => {
  const iconMap: { [key: string]: string } = {
    'arrow-back': '⬅️',
    'calendar': '📅',
  };

  return (
    <Text style={{ fontSize: size, color, textAlign: 'center' }}>
      {iconMap[name] || '📱'}
    </Text>
  );
};

const JiabanApplication: React.FC = () => {
  const navigation = useNavigation();
  const [formData, setFormData] = useState({
    applicant: '',
    overtimeDate: '',
    startTime: '',
    endTime: '',
    overtimeDuration: '',
    reason: '',
  });

  // Picker states
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [showStartTimePicker, setShowStartTimePicker] = useState(false);
  const [showEndTimePicker, setShowEndTimePicker] = useState(false);

  // Date picker state
  const [selectedYear, setSelectedYear] = useState(2022);
  const [selectedMonth, setSelectedMonth] = useState(12);
  const [selectedDay, setSelectedDay] = useState(6);

  // Time picker state
  const [selectedHour, setSelectedHour] = useState(18);
  const [selectedMinute, setSelectedMinute] = useState(0);

  const years = Array.from({ length: 5 }, (_, i) => 2020 + i);
  const months = Array.from({ length: 12 }, (_, i) => i + 1);
  const days = Array.from({ length: 31 }, (_, i) => i + 1);
  const hours = Array.from({ length: 24 }, (_, i) => i);
  const minutes = Array.from({ length: 60 }, (_, i) => i);

  const getDaysInMonth = (year: number, month: number) => {
    return new Date(year, month, 0).getDate();
  };

  const handleDateSelect = (day: number) => {
    const formattedMonth = selectedMonth.toString().padStart(2, '0');
    const formattedDay = day.toString().padStart(2, '0');
    const newDate = `${selectedYear}-${formattedMonth}-${formattedDay}`;
    
    // 验证日期不能大于当前日期
    const selectedDate = new Date(selectedYear, selectedMonth - 1, day);
    const currentDate = new Date();
    currentDate.setHours(0, 0, 0, 0);
    
    if (selectedDate > currentDate) {
      Alert.alert('提示', '加班日期不能大于当前日期');
      return;
    }
    
    setFormData({ ...formData, overtimeDate: newDate });
    setShowDatePicker(false);
  };

  const handleTimeSelect = (isStartTime: boolean) => {
    const formattedHour = selectedHour.toString().padStart(2, '0');
    const formattedMinute = selectedMinute.toString().padStart(2, '0');
    const timeString = `${formattedHour}:${formattedMinute}`;
    
    if (isStartTime) {
      setFormData(prev => ({ ...prev, startTime: timeString }));
      setShowStartTimePicker(false);
    } else {
      setFormData(prev => ({ ...prev, endTime: timeString }));
      setShowEndTimePicker(false);
    }
    
    // 计算加班时长
    setTimeout(() => {
      if (isStartTime) {
        // 如果设置了开始时间，检查是否已有结束时间
        if (formData.endTime) {
          calculateDuration();
        }
      } else {
        // 如果设置了结束时间，检查是否已有开始时间
        if (formData.startTime) {
          calculateDuration();
        }
      }
    }, 100);
  };

  const calculateDuration = () => {
    if (formData.startTime && formData.endTime) {
      const [startHour, startMinute] = formData.startTime.split(':').map(Number);
      const [endHour, endMinute] = formData.endTime.split(':').map(Number);
      
      let startTotalMinutes = startHour * 60 + startMinute;
      let endTotalMinutes = endHour * 60 + endMinute;
      
      // 如果结束时间小于开始时间，说明跨天了
      if (endTotalMinutes < startTotalMinutes) {
        endTotalMinutes += 24 * 60;
      }
      
      const diffMinutes = endTotalMinutes - startTotalMinutes;
      const diffHours = Math.ceil(diffMinutes / 60);
      
      setFormData(prev => ({ ...prev, overtimeDuration: `${diffHours}小时` }));
    }
  };

  const validateForm = (): boolean => {
    if (!formData.applicant.trim()) {
      Alert.alert('提示', '请填写申请人姓名');
      return false;
    }
    if (!formData.reason.trim()) {
      Alert.alert('提示', '请填写加班原因');
      return false;
    }
    return true;
  };

  const saveToLocalStorage = async (data: any) => {
    try {
      const existingData = await AsyncStorage.getItem('applications');
      const applications = existingData ? JSON.parse(existingData) : [];
      
      const newApplication = {
        id: Date.now().toString(),
        type: '加班申请',
        title: '加班申请',
        applicant: formData.applicant,
        details: `${formData.overtimeDate} ${formData.startTime}-${formData.endTime} 共${formData.overtimeDuration}`,
        applicationTime: new Date().toLocaleString('zh-CN'),
        status: '待审批',
        data: data,
        category: '人事管理',
      };
      
      applications.unshift(newApplication);
      await AsyncStorage.setItem('applications', JSON.stringify(applications));
    } catch (error) {
      console.error('保存数据失败:', error);
    }
  };

  const handleSubmit = async () => {
    if (!validateForm()) {
      return;
    }

    try {
      await saveToLocalStorage(formData);
      Alert.alert('提示', '提交完成', [
        {
          text: '确定',
          onPress: () => (navigation as any).navigate('AllApplications'),
        },
      ]);
    } catch (error) {
      Alert.alert('错误', '提交失败，请重试');
    }
  };

  const renderDatePicker = () => {
    const daysInMonth = getDaysInMonth(selectedYear, selectedMonth);
    const availableDays = Array.from({ length: daysInMonth }, (_, i) => i + 1);

    return (
      <Modal
        visible={showDatePicker}
        transparent={true}
        animationType="slide"
        onRequestClose={() => setShowDatePicker(false)}
      >
        <TouchableOpacity
          style={styles.modalOverlay}
          activeOpacity={1}
          onPress={() => setShowDatePicker(false)}
        >
          <View style={styles.datePickerContainer}>
            {/* Header with confirm button */}
            <View style={styles.datePickerHeader}>
              <Text style={styles.datePickerTitle}>选择加班日期</Text>
              <TouchableOpacity onPress={() => setShowDatePicker(false)}>
                <Text style={styles.confirmButton}>确定</Text>
              </TouchableOpacity>
            </View>
            
            {/* Year and Month Selector */}
            <View style={styles.dateSelectorHeader}>
              <View style={styles.dateSelector}>
                <Text style={styles.dateSelectorLabel}>年份:</Text>
                <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                  <View style={styles.dateOptions}>
                    {years.map(year => (
                      <TouchableOpacity
                        key={year}
                        style={[
                          styles.dateOption,
                          selectedYear === year && styles.selectedDateOption
                        ]}
                        onPress={() => setSelectedYear(year)}
                      >
                        <Text style={[
                          styles.dateOptionText,
                          selectedYear === year && styles.selectedDateOptionText
                        ]}>
                          {year}
                        </Text>
                      </TouchableOpacity>
                    ))}
                  </View>
                </ScrollView>
              </View>
              
              <View style={styles.dateSelector}>
                <Text style={styles.dateSelectorLabel}>月份:</Text>
                <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                  <View style={styles.dateOptions}>
                    {months.map(month => (
                      <TouchableOpacity
                        key={month}
                        style={[
                          styles.dateOption,
                          selectedMonth === month && styles.selectedDateOption
                        ]}
                        onPress={() => setSelectedMonth(month)}
                      >
                        <Text style={[
                          styles.dateOptionText,
                          selectedMonth === month && styles.selectedDateOptionText
                        ]}>
                          {month}
                        </Text>
                      </TouchableOpacity>
                    ))}
                  </View>
                </ScrollView>
              </View>
            </View>

            {/* Days Grid */}
            <View style={styles.daysContainer}>
              <View style={styles.weekDays}>
                {['日', '一', '二', '三', '四', '五', '六'].map(day => (
                  <Text key={day} style={styles.weekDayText}>{day}</Text>
                ))}
              </View>
              <View style={styles.daysGrid}>
                {availableDays.map(day => (
                  <TouchableOpacity
                    key={day}
                    style={styles.dayButton}
                    onPress={() => handleDateSelect(day)}
                  >
                    <Text style={styles.dayButtonText}>{day}</Text>
                  </TouchableOpacity>
                ))}
              </View>
            </View>
          </View>
        </TouchableOpacity>
      </Modal>
    );
  };

  const renderTimePicker = (visible: boolean, onClose: () => void, onConfirm: () => void) => (
    <Modal
      visible={visible}
      transparent={true}
      animationType="slide"
      onRequestClose={onClose}
    >
      <TouchableOpacity
        style={styles.modalOverlay}
        activeOpacity={1}
        onPress={onClose}
      >
        <View style={styles.timePickerContainer}>
          <View style={styles.timePickerHeader}>
            <Text style={styles.timePickerTitle}>选择时间</Text>
            <TouchableOpacity onPress={onConfirm}>
              <Text style={styles.confirmButton}>确定</Text>
            </TouchableOpacity>
          </View>
          
          <View style={styles.timePickerContent}>
            <View style={styles.timePickerColumn}>
              {hours.map(hour => (
                <TouchableOpacity
                  key={hour}
                  style={[
                    styles.timePickerItem,
                    selectedHour === hour && styles.selectedTimeItem
                  ]}
                  onPress={() => setSelectedHour(hour)}
                >
                  <Text style={[
                    styles.timePickerItemText,
                    selectedHour === hour && styles.selectedTimeItemText
                  ]}>
                    {hour.toString().padStart(2, '0')}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
            <Text style={styles.timePickerSeparator}>:</Text>
            <View style={styles.timePickerColumn}>
              {minutes.map(minute => (
                <TouchableOpacity
                  key={minute}
                  style={[
                    styles.timePickerItem,
                    selectedMinute === minute && styles.selectedTimeItem
                  ]}
                  onPress={() => setSelectedMinute(minute)}
                >
                  <Text style={[
                    styles.timePickerItemText,
                    selectedMinute === minute && styles.selectedTimeItemText
                  ]}>
                    {minute.toString().padStart(2, '0')}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>
        </View>
      </TouchableOpacity>
    </Modal>
  );

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor="#fff" />
      
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity 
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Icon name="arrow-back" size={20} color="#333" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>加班申请</Text>
        <View style={styles.headerSpacer} />
      </View>

      {/* Content */}
      <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
        {/* Basic Information Section */}
        <View style={styles.section}>
          <View style={styles.infoRow}>
            <Text style={styles.label}>申请人</Text>
            <TextInput
              style={styles.textInput}
              placeholder="请输入申请人姓名"
              placeholderTextColor="#999"
              value={formData.applicant}
              onChangeText={(text) => setFormData({...formData, applicant: text})}
            />
          </View>
          <View style={styles.separator} />
          
          <TouchableOpacity
            style={styles.infoRow}
            onPress={() => setShowDatePicker(true)}
          >
            <Text style={styles.label}>加班日期</Text>
            <View style={styles.infoValue}>
              <Text style={styles.valueText}>{formData.overtimeDate}</Text>
              <Icon name="calendar" size={16} color="#999" />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          
          <TouchableOpacity
            style={styles.infoRow}
            onPress={() => setShowStartTimePicker(true)}
          >
            <Text style={styles.label}>开始时间</Text>
            <View style={styles.infoValue}>
              <Text style={styles.valueText}>{formData.startTime}</Text>
              <Icon name="calendar" size={16} color="#999" />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          
          <TouchableOpacity
            style={styles.infoRow}
            onPress={() => setShowEndTimePicker(true)}
          >
            <Text style={styles.label}>结束时间</Text>
            <View style={styles.infoValue}>
              <Text style={styles.valueText}>{formData.endTime}</Text>
              <Icon name="calendar" size={16} color="#999" />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          
          <View style={styles.infoRow}>
            <Text style={styles.label}>加班时长</Text>
            <Text style={styles.valueText}>{formData.overtimeDuration}</Text>
          </View>
        </View>

        {/* Reason Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>加班原因</Text>
          <TextInput
            style={styles.textArea}
            placeholder="请输入"
            placeholderTextColor="#999"
            multiline
            numberOfLines={4}
            value={formData.reason}
            onChangeText={(text) => setFormData({...formData, reason: text})}
          />
        </View>

        {/* Approval Process Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>审批流程</Text>
          <View style={styles.approvalFlow}>
            <View style={styles.flowStep}>
              <View style={styles.flowNode}>
                <Text style={styles.flowNodeText}>1</Text>
              </View>
              <Text style={styles.flowLabel}>发起人</Text>
            </View>
            <View style={styles.flowArrow}>
              <Text style={styles.arrowText}>›</Text>
            </View>
            <View style={styles.flowStep}>
              <View style={styles.flowNode}>
                <Text style={styles.flowNodeText}>2</Text>
              </View>
              <Text style={styles.flowLabel}>部门领导</Text>
            </View>
            <View style={styles.flowArrow}>
              <Text style={styles.arrowText}>›</Text>
            </View>
            <View style={styles.flowStep}>
              <View style={styles.flowNode}>
                <Text style={styles.flowNodeText}>3</Text>
              </View>
              <Text style={styles.flowLabel}>人事部</Text>
            </View>
          </View>
        </View>

        {/* Submit Button */}
        <TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
          <Text style={styles.submitButtonText}>提交</Text>
        </TouchableOpacity>
      </ScrollView>

      {/* Pickers */}
      {renderDatePicker()}
      {renderTimePicker(
        showStartTimePicker,
        () => setShowStartTimePicker(false),
        () => handleTimeSelect(true)
      )}
      {renderTimePicker(
        showEndTimePicker,
        () => setShowEndTimePicker(false),
        () => handleTimeSelect(false)
      )}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  headerSpacer: {
    width: 28,
  },
  content: {
    flex: 1,
    paddingHorizontal: 16,
  },
  section: {
    marginTop: 20,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 12,
  },
  infoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 16,
  },
  label: {
    fontSize: 16,
    color: '#333',
    width: 80,
  },
  textInput: {
    flex: 1,
    fontSize: 16,
    color: '#333',
    textAlign: 'right',
  },
  infoValue: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  valueText: {
    fontSize: 16,
    color: '#333',
    marginRight: 8,
  },
  separator: {
    height: 1,
    backgroundColor: '#e0e0e0',
  },
  textArea: {
    borderWidth: 1,
    borderColor: '#e0e0e0',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    color: '#333',
    minHeight: 100,
    textAlignVertical: 'top',
  },
  approvalFlow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 16,
  },
  flowStep: {
    alignItems: 'center',
    flex: 1,
  },
  flowNode: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#6c5ce7',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 8,
  },
  flowNodeText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
  flowLabel: {
    fontSize: 12,
    color: '#333',
    textAlign: 'center',
  },
  flowArrow: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 20,
  },
  arrowText: {
    fontSize: 18,
    color: '#999',
  },
  submitButton: {
    backgroundColor: '#6c5ce7',
    borderRadius: 8,
    paddingVertical: 16,
    alignItems: 'center',
    marginTop: 32,
    marginBottom: 32,
  },
  submitButtonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  datePickerContainer: {
    backgroundColor: '#fff',
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    padding: 20,
    width: '100%',
    maxHeight: '80%',
  },
  datePickerHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
    paddingBottom: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  datePickerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  confirmButton: {
    fontSize: 16,
    color: '#6c5ce7',
    fontWeight: '600',
  },
  dateSelectorHeader: {
    marginBottom: 20,
  },
  dateSelector: {
    marginBottom: 15,
  },
  dateSelectorLabel: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 8,
  },
  dateOptions: {
    flexDirection: 'row',
  },
  dateOption: {
    paddingHorizontal: 12,
    paddingVertical: 8,
    marginRight: 8,
    borderRadius: 6,
    backgroundColor: '#f5f5f5',
  },
  selectedDateOption: {
    backgroundColor: '#6c5ce7',
  },
  dateOptionText: {
    fontSize: 14,
    color: '#333',
  },
  selectedDateOptionText: {
    color: '#fff',
    fontWeight: '600',
  },
  daysContainer: {
    flex: 1,
  },
  weekDays: {
    flexDirection: 'row',
    marginBottom: 10,
  },
  weekDayText: {
    flex: 1,
    textAlign: 'center',
    fontSize: 14,
    fontWeight: '600',
    color: '#666',
  },
  daysGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  dayButton: {
    width: '14.28%',
    aspectRatio: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 8,
  },
  dayButtonText: {
    fontSize: 16,
    color: '#333',
  },
  timePickerContainer: {
    backgroundColor: '#fff',
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    padding: 20,
  },
  timePickerHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
    paddingBottom: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  timePickerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  timePickerContent: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: 200,
  },
  timePickerColumn: {
    width: 80,
    height: 200,
  },
  timePickerItem: {
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  selectedTimeItem: {
    backgroundColor: '#6c5ce7',
    borderRadius: 20,
  },
  timePickerItemText: {
    fontSize: 16,
    color: '#333',
  },
  selectedTimeItemText: {
    color: '#fff',
    fontWeight: '600',
  },
  timePickerSeparator: {
    fontSize: 24,
    color: '#333',
    marginHorizontal: 20,
  },
});

export default JiabanApplication;
